import React, { useEffect } from 'react';
import { Form, Row, Col } from 'antd';
import request from '@/utils/request';
import { parse } from '@/pages/Organization/Role/utils';
import SearchTree from '@/pages/Organization/Role/component/SearchTree';
import styles from './postForm.less';

export default props => {
    const {
        doubleStyle,
        // isEdit,
        isDetail,
        form: { getFieldDecorator },
        detail = {},
        query: { action }
    } = props;

    const [menuList, setMenuList] = React.useState([]);
    const [authMenu, setAuthMenu] = React.useState([]);

    useEffect(() => {
        (async () => {
            const response = await request('/api/oa/v1/post/auth/getTree', {
                method: 'post'
            });
            if (response.code === 10000) {
                setMenuList(response.data);
            }
        })();
    }, []);

    useEffect(() => {
        if (action === '' || !action) {
            const getDefaultAuthMenu = async () => {
                const response = await request('/api/oa/v1/post/auth/getDefaultAuth', {
                    method: 'post'
                });
                if (response.code === 10000) {
                    return response.data;
                }
                return [];
            };
            getDefaultAuthMenu().then(res => {
                setAuthMenu(res);
            });
        }
    }, [action]);

    useEffect(() => {
        const { menuList: mlist = [] } = detail;
        if (mlist.length) {
            setAuthMenu(mlist);
        }
    }, [detail]);

    return (
        <>
            <div className={styles.formBlockTitle}>权限管理</div>
            <Row>
                <Col span={12}>
                    <Form.Item required label="功能权限" {...doubleStyle}>
                        {getFieldDecorator('menuList', {
                            // initialValue: isEdit ? authMenu : defaultAuthMenu,
                            initialValue: authMenu,
                            trigger: 'onCheck',
                            valuePropName: 'valueProps',
                            rules: [
                                {
                                    validator(_, value = [], callback) {
                                        if (Array.isArray(value) && value.length > 0) {
                                            callback();
                                        } else {
                                            callback('请选择功能权限！');
                                        }
                                    }
                                }
                            ]
                        })(<SearchTree disabled={isDetail} list={parse(menuList)} />)}
                    </Form.Item>
                </Col>
            </Row>
        </>
    );
};
